package xx.codeflower.whois;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Scanner;

import processing.xml.XMLElement;

import com.briansteen.utils.GeoPosition;

/**
 * 
 * @author Denny Koch
 * 
 * Send an ip and get back a com.briansteen.utils.GeoPosition
 *
 */
public class WhoisRequest {
	
	
	// Quick 'n dirty 
	public GeoPosition get(String ip) {
		
		String res = "";
		GeoPosition gps = new GeoPosition(0, 0);
		
		System.out.println("WhoisRequest: trying to locate ip: "+ip);
		
		InputStream is = null;		  
		try {
			URL url = new URL("http://iplocationtools.com/ip_query.php?ip="+ip); 
			is = url.openStream(); 
			res = new Scanner( is ).useDelimiter( "\\Z" ).next(); 
		} catch ( Exception e ) { 
			e.printStackTrace();
		} finally {
			if ( is != null ) 
				try { is.close(); } catch ( IOException e ) { } 
		} 		
	
		String city = "unknown";
		
		XMLElement xml = new XMLElement(res);
		  int numSites = xml.getChildCount();
		  for (int i = 0; i < numSites; i++) {
		    XMLElement kid = xml.getChild(i);
		    if(i==6) city = kid.getContent();
		    if(i==8) gps.latitude = Float.parseFloat(kid.getContent());
		    if(i==9) gps.longitude = Float.parseFloat(kid.getContent());
		  }
		  
		  System.out.println("WhoisRequest: found "+ip+" in "+city+ " at "+gps);
		  
		return gps;
	}
	
}
